package com.yunkaweilai.android.activity.operation;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.Target;
import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.PreferencesUtils;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.MainActivity;
import com.yunkaweilai.android.activity.lanya.LanyaSetting;
import com.yunkaweilai.android.activity.operation.consumption.jici.JiciMemberActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.constants.GlobalVariable;
import com.yunkaweilai.android.model.print.ReceivablesPrintModel;
import com.yunkaweilai.android.model.print.TemplateInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.SoundPlayUtils;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.utils.print.PrintExecutor;
import com.yunkaweilai.android.utils.print.PrinterWriter58mm;
import com.yunkaweilai.android.utils.print.PrinterWriter80mm;
import com.yunkaweilai.android.utils.print.data.ReceivablesPrintMaker;
import com.yunkaweilai.android.utils.zxing.Kutils;
import com.yunkaweilai.android.view.dialog.CouponListDialog;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 扣次成功
 * Created by Administrator on 2017/7/17.
 */

public class ReduceJiciSuccessActivity extends BaseActivity {


    @BindView(R.id.id_tv_order_no)
    TextView idTvOrderNo;
    @BindView(R.id.id_tv_time)
    TextView idTvTime;
    @BindView(R.id.id_tv_operation_man)
    TextView idTvOperationMan;
    @BindView(R.id.id_tv_close)
    TextView idTvClose;
    @BindView(R.id.id_tv_continue)
    TextView idTvContinue;
    @BindView(R.id.titlebar_iv_left)
    ImageView titlebarIvLeft;
    @BindView(R.id.titlebar_tv_left)
    TextView titlebarTvLeft;
    @BindView(R.id.titlebar_tv)
    TextView titlebarTv;
    @BindView(R.id.titlebar_iv_right_2)
    ImageView titlebarIvRight2;
    @BindView(R.id.titlebar_iv_right)
    ImageView titlebarIvRight;
    @BindView(R.id.titlebar_tv_right)
    TextView titlebarTvRight;
    @BindView(R.id.id_view_underline)
    View idViewUnderline;
    @BindView(R.id.rl_titlebar)
    RelativeLayout rlTitlebar;
    @BindView(R.id.id_tv_print)
    TextView idTvPrint;
    @BindView(R.id.id_tv_success)
    TextView idTvSuccess;
    @BindView(R.id.content_view)
    LinearLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.tv_add_member)
    TextView TextViewAddMember;
    @BindView(R.id.line_add_member)
    LinearLayout LinearLayoutAddMember;
    @BindView(R.id.line_add_yhq)
    LinearLayout LinearLayoutAddYhq;
    @BindView(R.id.tv_add_yhq)
    TextView TextViewAddYhq;
    //    @BindView(R.id.tv_add_see)
//    TextView TextViewAddSee;
    @BindView(R.id.line_sanke)
    LinearLayout linearLayoutSanKe;
    @BindView(R.id.line_member)
    LinearLayout linearLayoutMember;
    @BindView(R.id.id_tv_card_money)
    TextView TvCardMoney;
    @BindView(R.id.id_tv_card_score)
    TextView TvCardScore;
    //    @BindView(R.id.id_tv_send_coupon)
//    TextView TvCardSendCoupon;
    @BindView(R.id.id_tv_send_coupon_left)
    TextView TvCardSendCouponLeft;
    @BindView(R.id.id_tv_card_have)
    TextView TvCardHave;
    private boolean sms = false;
    private boolean wechat = false;
    private boolean print = false;

    private String orderno;

    private File imageFile;
    private Gson gson = new Gson();
    private ReceivablesPrintModel receivablesPrintModel;
    private ReceivablesPrintMaker maker;
    private TemplateInfoModel templateInfoModel;//打印小票设置


    public static void actionStart(Context context, String orderno, boolean sms, boolean wechat,boolean print) {
        Intent intent = new Intent(context, ReduceJiciSuccessActivity.class);
        intent.putExtra(GlobalVariable.RECHARGE_ORDER_NO, orderno);
        Bundle bundle = new Bundle();
        bundle.putBoolean(GlobalVariable.SMS, sms);
        bundle.putBoolean(GlobalVariable.WECHAT, wechat);
        bundle.putBoolean(GlobalVariable.PRINT, print);
        intent.putExtra("double", bundle);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reduce_success);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        orderno = intent.getStringExtra(GlobalVariable.RECHARGE_ORDER_NO);
        Bundle bundle = intent.getBundleExtra("double");
        sms = bundle.getBoolean(GlobalVariable.SMS);
        wechat = bundle.getBoolean(GlobalVariable.WECHAT);
        print = bundle.getBoolean(GlobalVariable.PRINT);
        initHead();

        ArrayList<BluetoothDevice> data = new ArrayList<>();
        data.addAll(bluetoothAdapter.getBondedDevices());
        String address = PreferencesUtils.getString(mAc, LanyaSetting.BLUETOOTH_ADDRESS);
        if (!StringUtils.isEmpty(address)) {
            for (int i = 0; i < data.size(); i++) {
                BluetoothDevice bluetoothDevice = data.get(i);
                if (bluetoothDevice.getAddress().equals(address)) {
                    mDevice = data.get(i);
                }
            }
        }
        if (mDevice != null) {
            idTvPrint.setText("打印小票(" + mDevice.getName() + ")");
        }


        idTvOrderNo.setText(orderno + "");
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp2();
            }
        });
        initHttp2();
    }


    //获取打印模版
    private void initHttp(String consume_type) {
//        HttpRequest.postUrl(Api.PRINT_SMALL_TICKET)
        HttpRequest.postUrl(Api.PRINT_CHARGE_TICKET)
                .addParams("consume_type", consume_type)
//                .addParams("template_type", "ReceiptConsume")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            templateInfoModel = gson.fromJson(json, TemplateInfoModel.class);


                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {

                                        String url = templateInfoModel.getData().getInfo().getReceipt_image();
                                        url = url + "?imageView2/1/w/280/h/280/q/100";
                                        final Context context = getApplicationContext();
                                        FutureTarget<File> target = Glide.with(context)
                                                .load(url)
                                                .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
                                        imageFile = target.get();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    handler.sendEmptyMessage(0);//发送消息到handler，通知进度
                                }
                            }).start();
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });
    }

    //获取打印数据
    private void initHttp2() {
        HttpRequest.postUrl(Api.RECEIVABLES_ORDER_PRINT)
                .addParams("tid", orderno)
                .execute(new PostProcess.StringCallBack() {

                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            receivablesPrintModel = gson.fromJson(json, ReceivablesPrintModel.class);
                            initHttp(receivablesPrintModel.getData().getOrder_info().getConsume_type());

                            //查看会员和优惠券按钮
                            LinearLayoutAddYhq.setVisibility(View.VISIBLE);
                            linearLayoutMember.setVisibility(View.VISIBLE);
                            linearLayoutSanKe.setVisibility(View.GONE);
//                                TextViewAddSee.setOnClickListener(new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View view) {
//                                        MemberCardDialog memberCardDialog = new MemberCardDialog(mAc, receivablesPrintModel.getData().getMember_info(), MemberCardDialog.TYPE_1);
//                                        memberCardDialog.show();
//                                    }
//                                });
                            //如果是会员，出现发送优惠券的按钮
                            TextViewAddYhq.setText(">>手动发优惠券<<");
                            TextViewAddYhq.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    CouponListDialog couponListDialog = new CouponListDialog(mAc, receivablesPrintModel.getData().getMember_info().getId(), receivablesPrintModel.getData().getMember_info().getMember_name(), sms, wechat);
                                    couponListDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                                    couponListDialog.show();
                                }
                            });

                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    maker = new ReceivablesPrintMaker(mAc, 50, 50, templateInfoModel, receivablesPrintModel, imageFile);
                    initView();
                    break;
                default:
                    break;
            }
        }
    };

    private void initView() {
//        idTvOrderNo.setText(orderno + "");
//        idTvOperationMan.setText(receivablesPrintModel.getData().getOrder_info().getCreate_name() + "");
//        idTvTime.setText(receivablesPrintModel.getData().getOrder_info().getConsume_time() + "");

        TvCardMoney.setText(receivablesPrintModel.getData().getMember_info().getMember_price());
        TvCardScore.setText(receivablesPrintModel.getData().getMember_info().getMember_points());
        if (receivablesPrintModel.getData().getOrder_info().getSend_coupon_title().size() == 0) {
            TvCardSendCouponLeft.setText("已发优惠券：无");
        } else {
            String s = "";
            for (int i = 0; i < receivablesPrintModel.getData().getOrder_info().getSend_coupon_title().size(); i++) {
                if (i < receivablesPrintModel.getData().getOrder_info().getSend_coupon_title().size() - 1) {
                    s = s + "已发优惠券：" + receivablesPrintModel.getData().getOrder_info().getSend_coupon_title().get(i) + "<br>";
                } else {
                    s = s + "已发优惠券：" + receivablesPrintModel.getData().getOrder_info().getSend_coupon_title().get(i);
                }
            }
            TvCardSendCouponLeft.setTextColor(getResources().getColor(R.color.calu_red));
            TvCardSendCouponLeft.setText(Html.fromHtml(s));
        }
        String x = "";
        if (!StringUtils.isEmpty(receivablesPrintModel.getData().getMember_info().getMember_jici()) && !StringUtils.isEmpty(Kutils.DealJici(receivablesPrintModel.getData().getMember_info().getMember_jici()))) {
            x = x + "剩余计次：" + Kutils.DealJici(receivablesPrintModel.getData().getMember_info().getMember_jici());
        }
        if (!StringUtils.isEmpty(receivablesPrintModel.getData().getMember_info().getMember_jishi())) {
            x = x + "<br>剩余计时：" + receivablesPrintModel.getData().getMember_info().getMember_jishi();
        }
        if (!StringUtils.isEmpty(receivablesPrintModel.getData().getMember_info().getMember_baoshiduan())) {
            x = x + "<br>剩余包时段：" + receivablesPrintModel.getData().getMember_info().getMember_baoshiduan();
        }
        if (StringUtils.isEmpty(x)) {
            TvCardHave.setText("卡内项目：无");
        } else {
            x = x.replaceAll(",", "，");
            TvCardHave.setText(Html.fromHtml(x));
        }

        if (idMultipleStatusView != null) {
            idMultipleStatusView.showContent();
        }
        SoundPlayUtils.play(1);
        boolean bluePrintFlg = PreferencesUtils.getBoolean(mAc, CommonConstants.CONSUME_DAYING, false);
        if (bluePrintFlg) {
            checkBluetooth();
        }
    }


    @Override
    public void onBackPressed() {
        return;
    }


    private void initHead() {
        new TitleBuilder(mAc).setTitleText("收款成功");
    }

    @OnClick({R.id.id_tv_close, R.id.id_tv_continue, R.id.id_tv_print})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_tv_close:
                intent2Activity(MainActivity.class);
                finish();
                break;
            case R.id.id_tv_continue:
                intent2Activity(JiciMemberActivity.class);
//                CommonMemberActivity.actionstart(mAc,CommonMemberActivity.TYPE_JICI_MEMBER);
                finish();
                break;
            case R.id.id_tv_print:
                if (print) {
                    checkBluetooth();
                }
                break;
        }
    }


    private final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private BluetoothDevice mDevice;
    private PrintExecutor executor;

    //蓝牙
    private void checkBluetooth() {
        if (bluetoothAdapter == null) {
            showToast("不支持蓝牙");
            return;
        }
        if (bluetoothAdapter.isEnabled()) {
            // 打印数据
            printData();
        } else {
            forceTurnOnBluetooth();//申请蓝牙
        }
    }

    private void printData() {

        if (mDevice == null) {
            showToast("未连接设备");
            return;
        }
        if (executor == null) {
            boolean aBoolean = PreferencesUtils.getBoolean(mAc, CommonConstants.LANYA_DAYING_58OR80, false);
            if (aBoolean) {
                executor = new PrintExecutor(mDevice, PrinterWriter80mm.TYPE_80);
            } else {
                executor = new PrintExecutor(mDevice, PrinterWriter58mm.TYPE_58);
            }
            executor.setOnPrintResultListener(new PrintExecutor.OnPrintResultListener() {
                @Override
                public void onResult(int errorCode) {
                }
            });
        }
        executor.setDevice(mDevice);
        int num = Integer.parseInt(templateInfoModel.getData().getInfo().getPrinter_count());
        for (int i = 0; i < num; i++) {//打印张数
            Log.d(TAG, "printData: " + num);
            executor.doPrinterRequestAsync(maker);
        }
    }

    private void forceTurnOnBluetooth() {
        final boolean open = bluetoothAdapter.isEnabled() || bluetoothAdapter.enable();
        if (!open) {
            showSystemTurnOnBluetoothDialog();
        }
    }

    private void showSystemTurnOnBluetoothDialog() {
        Intent requestBluetoothOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        requestBluetoothOn.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        requestBluetoothOn.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);
        startActivity(requestBluetoothOn);
    }
}
